﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading.Tasks;

namespace DataFeedService
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class MarketDataService : IMarketData, IDisposable
    {
        private static readonly SynchronizedCollection<IClientCallback> subscribers = new SynchronizedCollection<IClientCallback>();

        private DataSourceListener listener;

        public MarketDataService()
        {
            listener = new DataSourceListener(new DataSource(), update => UpdateSubscribers(update));
        }

        private void UpdateSubscribers(TickUpdate update)
        {
            try
            {
                lock (subscribers)
                {
                    Parallel.ForEach<IClientCallback>(subscribers, callback =>
                    {
                        if (((ICommunicationObject)callback).State == CommunicationState.Opened)
                        {
                            callback.SendTickUpdate(update);
                        }
                        else
                        {
                            subscribers.Remove(callback);
                        }
                    });
                }
            }
            catch { throw; }
        }

        #region IMarketData
        public void Subscribe()
        {
            try
            {
                IClientCallback callback = OperationContext.Current.GetCallbackChannel<IClientCallback>();

                lock (subscribers)
                {
                    if (!subscribers.Contains(callback))
                    {
                        subscribers.Add(callback);
                    }
                }
            }
            catch { throw; }
        }

        public void Unsubscribe()
        {
            try
            {
                IClientCallback callback = OperationContext.Current.GetCallbackChannel<IClientCallback>();

                lock (subscribers)
                {
                    if (subscribers.Contains(callback))
                    {
                        subscribers.Remove(callback);
                    }
                }
            }
            catch { throw; }
        }
        #endregion

        #region IDisposable
        public void Dispose()
        {
            listener.Dispose();   
        } 
        #endregion        
    }
}
